package net.easyjava.framework.third.sms;

import net.easyjava.framework.utils.ProjectProperties;
import net.easyjava.third.sms.zhutong.ZhuTongSMSClient;
import org.apache.commons.pool.impl.StackKeyedObjectPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by ludi on 16/7/26.
 */
public class ZhuTongSMSUtils {
    static Logger logger = LoggerFactory.getLogger(ZhuTongSMSUtils.class);
    private static ZhuTongSMSClient client;
    private static ProjectProperties properties;
    private static String username;
    private static String password;
    private static String codeProductId;
    private static String messageProductId;
    private static String content;

    /**
     * 初始化参数
     */
    private static void init(){
        if(client == null){
            initClient();
        }
    }
    private static synchronized void initClient(){
        if(client == null){
            properties = ProjectProperties.getInstance();
            if(username == null){
                username = properties.getProperty(ZhuTongSMSConstans.PROPERTIES_KEY_USERNAME);
            }
            if(password == null){
                password = properties.getProperty(ZhuTongSMSConstans.PROPERTIES_KEY_PASSWORD);
            }
            if (codeProductId == null) {
                codeProductId = properties.getProperty(ZhuTongSMSConstans.PROPERTIES_KEY_CODE_PRODUCTID);
            }
            if (messageProductId == null) {
                messageProductId = properties.getProperty(ZhuTongSMSConstans.PROPERTIES_KEY_MESSAGE_PRODUCTID);
            }
            client = ZhuTongSMSClient.getInstance(username, password, codeProductId, messageProductId);
        }
    }

    /**
     * 发送短信验证码
     * @param mobile 手机号
     * @param content 短信内容
     * @return
     */
    public static boolean sendCode(String mobile,String content) {
        try {
            init();
            client.sendCode(mobile, content);
            return true;
        } catch (Exception e) {
            logger.error("发送短信验证码失败,mobile:{},content:{}",mobile,content);
            logger.error(e.getMessage(),e.getCause());
            return false;
        }
    }

    /**
     *
     * @param mobile
     * @param content
     * @return
     */
    public static boolean sendMessage(String mobile, String content) {
        try {
            init();
            client.sendMessage(mobile, content);
            return true;
        } catch (Exception e) {
            logger.error("发送短信失败,mobile: {},content: {}", mobile, content);
            logger.error(e.getMessage(), e.getCause());
            return false;
        }
    }

}
